<template>
  <div class="message-content text-message-content">
    <div class="text-message-content-text" v-html="textMessage"></div>
  </div>
</template>

<script>
/** util */
import { emojiNames } from '@src/modules/im/imChat/utils/tools.js'

export default {
  name: 'text-message',
  props: {
    msgInfo: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
    };
  },
  computed:{
    textMessage(){
      return this.replaceURLWithHTMLLinks(this.msgInfo.messageContent.msg)
    }
  },
  methods: {
    // 将匹配结果替换表情图片
    emotion(res) {
      let word = res.replace(/\[|\]/gi, '');
      let index = emojiNames.indexOf(word);
      if (~index) {
        return `<img src="/resource/images/emoji/${index}.gif" align="middle">`;
      }
      // 没有匹配到表情
      return word;
    },
    replaceURLWithHTMLLinks(text) {
      let httpReg = new RegExp(
        '(http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&amp;*+?:_/=<>]*)?',
        'gi'
      ); // 用于判断文本内容超链接

      if (httpReg.test(text)) {
        // 文本地址变为a链接
        return text.replace(httpReg, function (httpText) {
          return `<a href="${httpText}" target="_blank">${httpText}</a>`;
        });
      }
      // 文本,匹配表情
      return text.replace(/\[[\u0041-\u9FA5]{1,3}\]/gi, this.emotion);
    },
  },
};
</script>

<style scoped lang='scss'>
.text-message-content-text{
  white-space: pre-wrap;
}
</style>